<?php
/**
 *
 * @author 
 *        
 *
 *        
 */
class Purchase{
	public static function change_status($way)
	{
       switch ($way)
		{
			case "货到付款":
  			$p_way =1;
  			break;
			case "周结":
  			$p_way =2;
  			break;
			case "网上支付":
  			$p_way =3;
  			break;
			case "款到发货":
  			$p_way =4;
  			break;
			case "月结":
  			$p_way =5;
  			break;
			case "货到付现":
  			$p_way =6;
  			break;
			case "货到转账":
  			$p_way =7;
  			break;
			case "半月结":
  			$p_way =8;
  			break;
			case "月结45天":
  			$p_way =12;
  			break;
			case "月结30天":
  			$p_way =11;
  			break;			
			case "月结60天":
  			$p_way =13;
  			break;
			default: $p_way =0;			
		}
		return $p_way;
	}
	/**
	 * 取消采购单
	 */
	public static function cancel_purchase($p_detail_id)
	{
		//付款了没入库 不允许取消
		//已付金额
		//付款金额大于入库金额 不允许取消
		$sql    = "SELECT * FROM `purchaseorder_details` WHERE `id`= ".$p_detail_id;

		//print_r($sql);exit();
		$data = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
		$sql  = "SELECT `id` FROM `pu_status` WHERE 1 AND `pu_id` = '".$data['purchaseorder_id']."'";

		$is_pay = DB::query(Database::SELECT,$sql)->execute('accountsystem')->current();
		if($is_pay){
			return 1;
		}

		//查找不良品库存
		$bad_stock = inventory::select_bad_product_stock($data['purchaseorder_id'],$data['sku']);

		//if($data['status']<40 || $data['status'] == 65)
		if($bad_stock==0 AND $data['status']<70 && $data['recieve_quantity']-$data['return_quantity']-$data['ware_quantity']==0)
		{
			$remark=0;
			if($data['status']<40)
			{
//				$sql_paid     = "SELECT `amount_paid`  FROM `purchase_pays` WHERE `purchase_detail_id` = ".$p_detail_id;
//				$paid         = DB::query(Database::SELECT,$sql_paid)->execute('newerp')->get('amount_paid');
//				if(empty($paid))
//				{
//					$remark = 100;					
//					$sql = "UPDATE `purchaseorder_details` SET `status`=100 WHERE `id` =".$p_detail_id;
//				}
//				else
//				{
//					return 1;
//				}
				if($data['recieve_quantity']>0){
					$remark = 90;
					
				}else{
					$remark = 100;
					
				}
					
				$sql = "UPDATE `purchaseorder_details` SET `status`='".$remark."' WHERE `id` =".$p_detail_id;
			}
			else
			{
				$remark = 90;
				$sql = "UPDATE `purchaseorder_details` SET `status`=90 WHERE `id` =".$p_detail_id;
			/*	$money = ($data['ware_quantity']/$data['quantity'])*$data['money'] ;
				$transportation_expense = ($data['ware_quantity']/$data['quantity'])*$data['transportation_expense'];
				$sql_update_money =  "UPDATE `purchaseorder_details` 
						SET `transportation_expense`='".$transportation_expense."',`money`='".$money."' 
						WHERE `id` = ".$p_detail_id;
				DB::query(Database::UPDATE,$sql_update_money)->execute('newerp');*/
			}
			DB::query(Database::UPDATE,$sql)->execute('newerp');
			if($remark==100){
				Settle::change_detail_money($p_detail_id,$data,$remark);//更新采购单以及详情单的数据,取消只修改状态，不能修改数量和金额

			}
			//Settle::change_detail_money($p_detail_id,$data,$remark);//更新采购单以及详情单的数据,取消只修改状态，不能修改数量和金额
			$sql = "SELECT `status` 
							FROM `purchaseorder_details` 
							WHERE `purchaseorder_id` =".$data['purchaseorder_id'];
			$status = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
			$flag = 0;$mark = 0;$sign = 0;
			foreach($status as $st)
			{
				if($st['status'] < 70)
				{
						return  $remark;
				}
				if($st['status'] == 90)
				{
						$flag = 1;
				}
				if($st['status'] == 100)
				{
						$mark = 1;
				}
				if($st['status'] == 70) 
				{
						$sign = 1;
				}
			}
			if($sign == 1)
			{
					$condition = 70;
			}
			else if($flag == 1)
			{
					$condition = 90;
			}
			else if($mark == 1)
			{
					$condition = 100;
			}
			$sql = "UPDATE `purchaseorders` SET `status`=".$condition." WHERE `id` =".$data['purchaseorder_id'];
			DB::query(Database::UPDATE,$sql)->execute('newerp');
			return $remark;			
		}
		else
		{
			return 1;
		}		
	}
	/**
	 * 修改采购单
	 */
	public static function change_purchase($p_id)
	{
		
			$sql = "SELECT * FROM `purchaseorder_details` WHERE `purchaseorder_id` = ".$p_id;
			$sql.=" order by id desc";
			$purchase_detail = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();						
			return $purchase_detail;
	}
	/**
	 * 查询采购单信息
	 */
	public static function select_purchase_info($p_id)
	{
		$purchase = Config::load('purchase_status');

        /**
         * 付款方式从数据库获取
         * 之前是写在配置文件中
         */
		//$pay_way  = $purchase->pay_way;
		$sql_select = "SELECT * FROM purchaseorders 
														WHERE id =".$p_id;
		$purchase_order = DB::query(Database::SELECT,$sql_select)
			->execute('newerp')
			->current();
		$user_name = ORM::factory("user",$purchase_order['purchase_id']);
		//echo $user->name;
		/*$sql_select     = "SELECT `name` FROM `gl_users` 
											WHERE `id`= '".$purchase_order['purchase_id']."'";
		$user_name      = DB::query(Database::SELECT,$sql_select)
			->execute()
			->get('name');*/

		$purchase_order['name']	= $user_name->nick;

        /**
         * 转换付款方式id=>string
         * id到显示的名称
         * @time 20140813
         */
        //$purchase_order['pay_way'] = $pay_way[$purchase_order['pay_way']];
        $pay_way = self::get_pay_way(array('id'=>$purchase_order['pay_way']));
        if($pay_way and isset($pay_way[0]['pay_way']))
        {
            $purchase_order['pay_way'] = $pay_way[0]['pay_way'];
        }
        else
        {
            $purchase_order['pay_way'] = '未知';
        }

		return $purchase_order;
	}

    /**
     * 查询付款方式
     * 如果有id或者汉字名称都可以查询
     * @param array $select
     * @return $this
     */
    public static function get_pay_way($select=array())
    {
//      -----------------------------kdw---------------------------
//        $re = DB::select(array('id','id'),array('type','pay_way'))
//            ->from('erp_pay_type');

        $re = DB::select(array('id','id'),array('paywayname','pay_way'))
            ->from('payways');
//      -----------------------------kdw-end-----------------------
        if(isset($select['id']) and is_array($select['id']))
        {
            $re = $re->where('id','in',$select['id']);
        }
        elseif(isset($select['id']))
        {
            $re = $re->where('id','=',(string)$select['id']);
        }

        if(isset($select['type']) and is_array($select['type']))
        {
//          ---------------------kdw--------------------
//            $re = $re->where('type','in',$select['type']);
            $re = $re->where('paywayname','in',$select['type']);
//          ---------------------kdw--------------------
        }
        elseif(isset($select['type']))
        {
//            -------------------------kdw------------------------
//            $re = $re->where('type','=',(string)$select['type']);
            $re = $re->where('paywayname','in',$select['type']);
//            -------------------------kdw-end--------------------
        }
//      ---------------kdw----------------
//        $re = $re->execute('readonlyerp')
//            ->as_array();
//      ---------------kdw-end------------
        $re = $re->execute('newerp')
            ->as_array();

        return $re;
    }
	/**
	 * 查询供应商信息
	 */
	public static function select_supplier($p_id)
	{
//      -----------------------------------------kdw---------------------------------------
//		$sql_select = "SELECT `supplier_id`
//									FROM `purchaseorders` WHERE id=".$p_id;
//		$supplier_id= DB::query(Database::SELECT,$sql_select)->execute('newerp')->get('supplier_id');
//
//		$sql_select = "SELECT * FROM `erp_provider` WHERE id=".$supplier_id;
//		$supplier   = DB::query(Database::SELECT,$sql_select)->execute('readonlyerp')->current();
        $supplier=array();

        //根据订单号获取到供应商id，联系人id，支付方式id，帐号信息id
        $sql="SELECT supplier_id,contact_id,payaccountinfo_id FROM purchasesupplier WHERE poid=$p_id";
        $relatedid=DB::query(Database::SELECT,$sql)->execute('newerp')->current();
        //查询采购单表获取到供应商id
        $sql = "SELECT supplier_id,pay_way FROM purchaseorders WHERE id=".$p_id;
        $purchase_info  = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
        if(!$relatedid){
            $supplier_info=supplierskus::getSuppliers(array('name,address'),array('id'=>"=".$purchase_info['supplier_id']));
            $supplier['vProviderName']=$supplier_info[0]['name'];
            $supplier['vAddress']=$supplier_info[0]['address'];

            //查询供应商联系人
            $contacts=Newerpclientapi::getSupplierContacts($purchase_info['supplier_id']);

            $supplier['vPhone']=$contacts[0]['phone'];
            $supplier['vFax']=$contacts[0]['fax'];
            $supplier['vContact']=$contacts[0]['contact'];
            $supplier['vMobile']=$contacts[0]['mobile'];

            //支付帐号信息
            $sql="SELECT bankname,bankaccountname,bankaccount FROM payaccountinfo WHERE id=
                            (SELECT payaccountinfo_id FROM supplierpayaccount WHERE supplier_id=".$purchase_info['supplier_id']." LIMIT 0,1)";

            $pay_indo=DB::query(Database::SELECT,$sql)->execute('newerp')->current();
            $supplier['vAccount']=$pay_indo['bankaccount'];
            $supplier['vEstablishBank']=$pay_indo['bankname'];
            $supplier['vAccountname']=$pay_indo['bankaccountname'];

        }else{
            //根据supplier_id获取供应商信息
            $supplier_info= supplierskus::getSuppliers(array('name','remark','address'),array('id'=>'='.$relatedid['supplier_id']));
            $supplier['vProviderName']=$supplier_info[0]['name'];
            $supplier['vAddress']=$supplier_info[0]['address'];
            $supplier['remark']=$supplier_info[0]['remark'];
//        Supplierbank::get_supplier_payways_by_supplier_id($p_id);//付款方式及银行账号
            //根据contact_id获取到联系人信息
            $contact= Newerpclientapi::getSupplierContacts($relatedid['supplier_id']);
            $contact = $contact?$contact[0]:array();
            $supplier['vPhone']=$contact['phone'];
            $supplier['vFax']=$contact['fax'];
            $supplier['vContact']=$contact['contact'];
            $supplier['vMobile']=$contact['mobile'];

            //根据payaccountinfo_id查询到支付帐号信息
//            $payaccountinfo=DB::query(Database::SELECT,
//                "SELECT bankname,bankaccountname,bankaccount FROM payaccountinfo WHERE id=".$relatedid['payaccountinfo_id'])
//                ->execute('newerp')->current();
            $payaccountinfo= Supplierbank::get_supplier_payways_by_supplier_id($relatedid['supplier_id']);
            foreach ($payaccountinfo as $k =>$v){
                if($v['payaccountinfo_id'] == $relatedid['payaccountinfo_id']){
                    $supplier['vEstablishBank']=$v['bankname'];
                    $supplier['vAccountname']=$v['bankaccountname'];
                    $supplier['vAccount']=$v['bankaccount'];
                }
            }


        }
        //获取到支付方式
        $sql="SELECT paywayname FROM payways WHERE id=".$purchase_info['pay_way'];
        $pay=DB::query(Database::SELECT,$sql)->execute('newerp')->current();
        $supplier['payment']=$pay['paywayname'];
//      -----------------------------------------kdw-end------------------------------------
		return $supplier;
	}
	//通过供应商id获取供应商name
	public static function select_s_name($s_id)
	{
//      -----------------------------------kdw-------------------------------------
//		$supplier = DB::select('vProviderName')->from('erp_provider')
//																->where('id','=',$s_id)
//																->execute('readonlyerp')
//																->get('vProviderName');
//      -----------------------------------kdw-end---------------------------------
        $name=Newerpclientapi::getSuppliers(array('name'),array('id'=>"=$s_id"));
//        $supplier=array('vProviderName'=>$name[0]['name']);
        $supplier = isset($name[0]['name'])?$name[0]['name']:'';
		return $supplier;
	}
	/**
	 * 查询产品信息
	 */
	public static function select_product($p_id)
	{
		$product_info = array();
		$sql_select = "SELECT `id`,`sku`,`quantity`,`single_price`,`sku_name`,`tax_way`,`status`,`details_date`,`tax_money`,supplier
									,sku_unit,`no_tax_money`,`money`,`arrive_date`,`tax_rate`,transportation_expense,item,real_tax_rate
										FROM `purchaseorder_details` 
										WHERE `purchaseorder_id` =".$p_id;	//print_r($sql_select);exit;
		$detail_info= DB::query(Database::SELECT,$sql_select)->execute('newerp')->as_array();

		foreach($detail_info as $value)
		{
			$sql        = "SELECT  `storage_position` as products_newplace
										FROM `purchaseorder_details` 
										WHERE `id` = ".$value['id']." AND `sku`='".$value['sku']."'";
			$product_data = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
			if(!is_array($product_data))
			{
				$product_data = array();
			}
			$sql        = "SELECT `recieve_quantity` as arrival_quantity 
										FROM `purchaseorder_details` 
										WHERE `id` = ".$value['id']." AND `sku`='".$value['sku']."'";
			$recieve_data = DB::query(Database::SELECT,$sql)->execute('newerp')->current();

			$sql 				= "SELECT `check_quantity` 
										FROM `purchaseorder_details` 
										WHERE `id`=".$value['id']." AND `sku`='".$value['sku']."'";		
			$check_data = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
			$sql 				= "SELECT `ware_quantity`
										FROM `purchaseorder_details` 
										WHERE `id`=".$value['id']." AND `sku`='".$value['sku']."'";		
			$ware_data = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
			/*$sql        = "SELECT SUM(`warehouse_quantity`) as warehouse_quantity FROM `warehouseorders` 
										WHERE `purchaseorders_id`=".$p_id." AND `sku`='".$value['sku']."'";
			$ware_data  = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
			if(!is_array($ware_data))
			{
				$ware_data['warehouse_quantity'] = "";
			}*/
			$sql = "SELECT `return_quantity` as qt
							FROM `purchaseorder_details` 
							WHERE `id`=".$value['id']." AND `sku`='".$value['sku']."'";
			$fail_data    = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
			$product_info[] = array_merge($value,$product_data,$recieve_data,$check_data,$ware_data,$fail_data);
						
		}
		return $product_info;
	}
	/**
	 * 查询采购付款单
	 */
	public static function select_pay($p_id)
	{
		$purchase = Config::load('purchase_status');
		$pay_way  = $purchase->pay_way;
		$pay_status= $purchase->purchase_pays;
		$sql_select = "SELECT * FROM `purchase_pays` WHERE `purchaseorder_id`=".$p_id;
		$pay_data   = DB::query(Database::SELECT,$sql_select)->execute('newerp')->as_array();
		if(!empty($pay_data))
		{
			foreach($pay_data as $key=>&$value)
			{
				$value['pay_way'] = $pay_way[$value['pay_way']]; 
			}
		}
		return $pay_data;
	}
	/**
	*查询采购退款单
	**/
	public static function select_refund($p_id)
	{
		$refund_info = DB::select()
									->from('refund_invoices')
									->where('purchaseorder_id','=',$p_id)
									->execute('newerp')->as_array();
		return $refund_info;
	}
	/**
	 * 查询付款以及退款总金额和状态
	 */
	public static function select_pay_purchase($p_id)
	{
		$status       = DB::select(DB::expr('status'))
									->from('pay_applicates')
									->where('purchaseorder_id','=',$p_id)
									->execute('newerp')->current();
		if(empty($status))
		{
			$status = array();
		}
		$pay_purchase = DB::select(DB::expr('SUM(amount_paid) as amount_paid'),'purchaseorder_id','amount_payable')
									->from('purchase_pays')
									->where('purchaseorder_id','=',$p_id)
									->execute('newerp')->current();
		if(empty($pay_purchase))
		{
			$pay_purchase = array();
		}
		$refund_purchase = DB::select(DB::expr('SUM(refund_money) as refund_money'))
									->from('refund_invoices')
									->where('purchaseorder_id','=',$p_id)
									->execute('newerp')->current();
		if(empty($refund_purchase))
		{
			$refund_purchase = array();
		}
		return array_merge($status,$pay_purchase,$refund_purchase);
	}

	/**
	 * 
	 */
	public static function sql_combine($sql,$arr)
	{
		foreach($arr as $key=>$value){
			if($value!=''){
				$sql .= " AND ".$key." = '".$value."' ";
			}else{
				continue;
			}
		}
		return $sql;
		//print_r($arr);
	}
	/**
	 * str-->date
	 */
	public static function revert_time($date)
	{
		$time = strtotime($date);
		return $time;
	}

	//更新采购单状态
	public static function update_po(array $arr_wo)
	{
		if(!isset($arr_wo['sku']) or !isset($arr_wo['poid']))
		{
			return;
		}
		//采购明细单
		$purchaseorder_detail = DB::select()
								->from('purchaseorder_details')
								->where('sku','=',$arr_wo['sku'])
								->where('purchaseorder_id','=',$arr_wo['poid'])
								->execute('newerp')
								->current();
		if(!$purchaseorder_detail)
		{
			return;
		}
		
		//回写入库数量
		DB::update('purchaseorder_details')
		->set(array('ware_quantity'=>$arr_wo['num']))
		->where('sku','=',$arr_wo['sku'])
		->where('purchaseorder_id','=',$arr_wo['poid'])
		->execute('newerp');
//echo $arr_wo['num'];exit;
		
		//以采购量或者以收货量，取其中较大
// 		$base_quantity = ($purchaseorder_detail['quantity']>$purchaseorder_detail['recieve_quantity'])?$purchaseorder_detail['quantity']:$purchaseorder_detail['recieve_quantity'];

		$base_quantity = $purchaseorder_detail['quantity'];
		//入库大于基准值
		if($arr_wo['num'] >= $base_quantity)
		{
			$flag_details = DB::update('purchaseorder_details')
			->set(array('status'=>70))
			->where('sku','=',$arr_wo['sku'])
			->where('purchaseorder_id','=',$arr_wo['poid'])
			->execute('newerp');
		}
		else
		{
			$flag_details = DB::update('purchaseorder_details')
			->set(array('status'=>65))
			->where('sku','=',$arr_wo['sku'])
			->where('purchaseorder_id','=',$arr_wo['poid'])
			->execute('newerp');
		}

		//采购单上面总共的明细数量
		$status_array = array(10,20,40,50,60,65,70);//有效采购单明细状态
		$count_all = DB::select(array(DB::expr('count(id)'),'count_all'))
					->from('purchaseorder_details')
					->where('purchaseorder_id','=',$arr_wo['poid'])
					->where('status','in',$status_array)
					->execute('newerp')
					->current();

		//已经完成的多少个
		$count = DB::select(array(DB::expr('count(id)'),'count'))
					->from('purchaseorder_details')
					->where('purchaseorder_id','=',$arr_wo['poid'])
					->where('status','=',70)
					->execute('newerp')
					->current();

		//采购单上面的明细全部已经入库，则采购单也入库
		if($count['count'] >= $count_all['count_all'])
		{
			$flag_purchaseorder = DB::update('purchaseorders')
			->set(array('status'=>70))
			->where('id','=',$arr_wo['poid'])
			->execute('newerp');
		}	
		// echo "OK";
		//exit;
		
		/**
		 * 系统自动计算交期并且保存到数据库
		 * 停止使用 @time2014-08-01
		 */
        /**
         * 正式停用了
         * @author zhjx
         * @time 20140918
         */
        /*$delivery = array();
        $delivery['purchaseorder_id'] = isset($purchaseorder_detail['purchaseorder_id'])?$purchaseorder_detail['purchaseorder_id']:-1;
        $delivery['supplier'] = isset($purchaseorder_detail['supplier'])?$purchaseorder_detail['supplier']:-1;
        $delivery['sku'] = isset($purchaseorder_detail['sku'])?$purchaseorder_detail['sku']:"";
        self::save_delivery($delivery);*/

        return "ok";
	}
	/*
	 * 获取采购单金额
	 */
	public static function select_total_purchase($p_id)
	{
		$sql ="SELECT SUM(money) as money ,SUM(transportation_expense) as transportation_expense 
						FROM `purchaseorder_details` 
						WHERE `purchaseorder_id` ='".$p_id."'  AND `status` !=100 ";
		$data = DB::query(Database::SELECT,$sql)->execute('newerp')->current();	
		return $data['money']	+ $data['transportation_expense'];				
	}
	/*
	 * 获取采购单已付金额
	 */
	public static function select_totals_purchase($p_id)
	{
		$sql ="SELECT SUM(`amount_paid`) as amount_paid  
					FROM `purchase_pays` 
					WHERE `purchaseorder_id` = '".$p_id."' 
					GROUP BY `purchase_detail_id` ";
		return DB::query(Database::SELECT,$sql)->execute('newerp')->get('amount_paid');
	}
	/*
	 * 获取采购单明细
	 */
	public static function select_purchase_detail($p_id)
	{
		$sql = "SELECT `id`,`sku`,`money`,`transportation_expense`  
						FROM `purchaseorder_details` 
						WHERE `purchaseorder_id` ='".$p_id."'  AND `status` !=100 ";
		$purchase_detail = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
		foreach($purchase_detail as $key =>&$value)
		{
			$value['money'] = $value['money']+$value['transportation_expense'];
		}
	//print_r($purchase_detail);exit;
		return $purchase_detail;
	}
	/*
	 * 获取采购单明细已付金额
	 */
	public static function select_paid($p_id)
	{
		$sql ="SELECT SUM(`amount_paid`) as amount_paid  
					FROM `purchase_pays` 
					WHERE `purchase_detail_id` = '".$p_id."' 
					GROUP BY `purchase_detail_id`";
		$paid =  DB::query(Database::SELECT,$sql)->execute('newerp')->get('amount_paid');
		return $paid;
	}
	/*
	 * 获取采购单明细金额
	 */
	public static function select_purchase_pay($p_id)
	{
		$sql = "SELECT `money`,`transportation_expense`  
						FROM `purchaseorder_details` 
						WHERE `id` ='".$p_id."'  AND `status` !=100 ";		//print_r($sql);exit;
		$purchase_pay = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
		$purchase_pay['money'] = $purchase_pay['money']+$purchase_pay['transportation_expense']; 

		return $purchase_pay['money'];
	}
	/*
	 * 状态判断
	 */
	public static function judge_status($purchaseorder_id)
	{
		$sql  ="SELECT `id` FROM `purchaseorder_details` WHERE `purchaseorder_id` = ".$purchaseorder_id ." AND status != 100 ";
		$infos=DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
		$flag = 1;
		foreach($infos as $info)
		{
			$id   = self::select_purchase_detail($purchaseorder_id);
			$paid = self::select_paid($info['id']);
			$pay  = self::select_purchase_pay($info['id']);
			if(empty($id))
				return 0;
			
			if($paid<$pay)
			{		
				$flag = 0; return $flag;
			}	
		}
		return 1;
	}

    /*
     * 此方法已经弃用
     */
	static function save_delivery (array $data)
	{
		if(!isset($data['purchaseorder_id'])
				or !isset($data['supplier'])
				or !isset($data['sku']) )
		{
			return NULL;
		}
	
		$sql_po = " SELECT purchaseorder_date ";
		$sql_po .= " FROM purchaseorders WHERE 1";
		$sql_po .= " 	AND id = ".$data['purchaseorder_id'];
		$sql_po .= " AND supplier_id = ".$data['supplier'];
// 		echo $sql_po;exit;
		$po_date = DB::query(Database::SELECT, $sql_po)->execute('newerp')->current();
		// 		$po_date = "";
	
		//采购时间
		if(empty($po_date) or !isset($po_date['purchaseorder_date']))
		{
			return NULL;
		}
	
		$sql_wo = " SELECT warehouse_date ";
		$sql_wo .= " FROM warehouseorders WHERE 1 ";
		$sql_wo .= " AND sku = '".trim($data['sku']). "' ";
		$sql_wo .= " AND purchaseorders_id = ".$data['purchaseorder_id'];
		$sql_wo .= " AND supplier_id = ".$data['supplier'];
		$sql_wo .= " ORDER BY warehouse_date ";
// 		echo $sql_wo;exit;
		$wo_date = DB::query(Database::SELECT, $sql_wo)->execute('newerp')->current();
	
		//入库时间
		if(empty($wo_date) or !isset($wo_date['warehouse_date']))
		{
			return NULL;
		}
		
// 		echo  strtotime($po_date['purchaseorder_date']);
// 		echo strtotime($wo_date['warehouse_date']);
		$on_way_time = (strtotime($wo_date['warehouse_date']) - strtotime($po_date['purchaseorder_date']))/(24*3600);
		$on_way_time = floor($on_way_time);
		
		$sql = " UPDATE erp_providerproducts ";
		$sql .= " SET delivery = (delivery+".$on_way_time.")/2 ";
		$sql .= " WHERE iproviderID= ".$data['supplier'];
		$sql .= " AND iproductID='".trim($data['sku']). "' ";
		DB::query(Database::UPDATE, $sql)->execute('readonlyerp');
		
	}

    /**
     * 通过采购单ID获取供应商信息
     * 拆分之前的通过供应商ID查询供应商信息的方法,不包含银行帐号信息
     * @author zhjx
     * @time 20140918
     */
    public static function get_provider_info_by_poid($poid,$supplier_id=NULL)
    {
         if(empty($poid))
         {
             return;
         }

        if(!$supplier_id)
        {
            $supplier_id = DB::select('id','supplier_id')
                ->from('purchaseorders')
                ->where('id','=',$poid)
                ->execute('newerp')
                ->current();
            if(!isset($supplier_id['id']))
            {
                 return;
            }
            if(isset($supplier_id['supplier_id']))
            {
                $supplier_id = $supplier_id['supplier_id'];
            }
        }

        if(empty($supplier_id))
        {
            return;
        }

        $provider = array();

        //获取选择的供应商信息
        $supplier=Newerpclientapi::getSuppliers(array('name,address'),array('id'=>"=".$supplier_id));
        $provider['vProviderName']=isset($supplier[0]['name'])?$supplier[0]['name']:'';
        $provider['vAddress']=isset($supplier[0]['address'])?$supplier[0]['address']:'';

        /**
         * 联系人信息
         */
        $contact_ids = array();
        $contact_id = DB::select('id','contact_id')
            ->from('purchasesupplier')
            ->where('poid','=',$poid)
            ->execute('newerp')
            ->current();
        if(isset($contact_id['contact_id']))
        {
            $contact_id = $contact_id['contact_id'];
            $contact_ids = Newerpclientapi::findContactById($contact_id);
        }
        else
        {
            $contact_ids = Newerpclientapi::getSupplierContacts($supplier_id);
            $contact_ids = isset($contact_ids[0])?$contact_ids[0]:NULL;
        }
        unset($contact_id);

        $provider['vPhone']=isset($contact_ids['phone'])?$contact_ids['phone']:'';
        $provider['vFax']=isset($contact_ids['fax'])?$contact_ids['fax']:'';
        $provider['vContact']=isset($contact_ids['contact'])?$contact_ids['contact']:'';
        $provider['vMobile']=isset($contact_ids['mobile'])?$contact_ids['mobile']:'';

        return $provider;

    }

    /**
     * @return mixed
     * 获取海外仓的仓库
	 * nirui20160927 16:56:00 update
     */
    public static function getOutLandStock() {
		$re = array();

		$re = DB::query(Database::SELECT, 'SELECT `store_id`,`store_name` FROM `branch_stores` WHERE 1')
			->execute('newerp')->as_array('store_id', 'store_name');

		$re[0] = '国内仓';

		return $re;
    }
	/*
	 * 根据采购单号获取采购员名称
	 */

	public static function getPurchase_nameByPurchaseorder_id($purchaseorder_id){
		$sql='SELECT purchase_id FROM purchaseorders WHERE id='.$purchaseorder_id;
		$purchase_id=DB::query(Database::SELECT,$sql)->execute('newerp')->get('purchase_id');
		$sql='SELECT nick FROM users WHERE id='.$purchase_id;
		$purchase_name=DB::query(Database::SELECT,$sql)->execute('default')->get('nick');
		return $purchase_name;
	}
}
